# coding=utf-8
from worldcup.apps.userModel.models import Article
from worldcup.commons.CommonResult import rest, CommonResult


@rest
def list_article(request):
	articles = Article.objects.values("id", "name", "survey", "date", "hits","category_name","survey_image").all()
	results = []
	for article in articles:
		results.append({
			"id": article["id"],
			"name": article["name"],
			"survey": article["survey"],
			"date": article["date"],
			"hits": article["hits"],
			"categoryName": article["category_name"],
			"surveyImage": article["survey_image"]
		})
	return CommonResult(0, results)


@rest
def group_article(request):
	articles = Article.objects.values("id", "name", "survey", "date", "hits", "category_name", "survey_image").all()
	group_article = {}
	for article in articles:
		category_name = article["category_name"]
		group_list = group_article.get(category_name)
		if group_list is None:
			group_list = []
			group_article[category_name] = group_list

		article = {
			"id": article["id"],
			"name": article["name"],
			"survey": article["survey"],
			"date": article["date"],
			"hits": article["hits"],
			"categoryName": article["category_name"],
			"surveyImage": article["survey_image"]
		}
		group_list.append(article)
	results = []
	for category_name, articles in group_article.items():
		if category_name == "亚洲杯":
			results.insert(0, {
				"categoryName": category_name,
				"articles": articles
			})
		else:
			results.append({
				"categoryName": category_name,
				"articles": articles
			})
	return CommonResult(0, results)

@rest
def get_article(request):
	id = request.GET.get("id")
	article = Article.objects.filter(id=id).get()

	article.hits = article.hits + 1
	article.save()
	return CommonResult(0, {
		"id": article.id,
		"name": article.name,
		"content": article.content,
		"date": article.date,
		"hits": article.hits,
		"categoryName": article.category_name
	})

